#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009 Denis Mingulov
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.1')

import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.ext.webapp import template

from google.appengine.ext.db import djangoforms

from engine import modules
from engine import persons

class MainHandler(webapp.RequestHandler):
    def get_page_data(self):

        pers = persons.getCurrentPerson()
        modlist = persons.getActiveModules(pers, True)
        
#        def mod_sort(x, y):
#            return x.__class__.__name__ < y.__class__.__name__
#        modlist.sort(cmp=mod_sort)

        for item in modlist:
            item.section = item.__class__.__name__

        menulist = ['Корабельные модули', ['<a href="#Weapon">Оружие</a>', ['<a href="#LaserWeapon">Лазерное</a>', '<a href="#PlasmaWeapon">Плазменное</a>', '<a href="#RocketWeapon">Ракетное</a>', '<a href="#MineWeapon">Минное</a>', '<a href="#EnergyWeapon">Энергетическое</a>', '<a href="#GravityWeapon">Гравитационное</a>'], '<a href="#Radar">Радары</a>', ['<a href="#BattleRadar">Боевые</a>', '<a href="#JammerRadar">Помехи</a>', '<a href="#NavigationRadar">Навигационные</a>', '<a href="#LongRangeRadar">Сверхдальние</a>'], '<a href="#PowerUnit">Энергоустановки</a>', '<a href="#Computer">Компьютеры</a>', ['<a href="#BattleComputer">Боевые</a>', '<a href="#NavigationComputer">Навигационные</a>'], '<a href="#Compartment">Жилые отсеки</a>', '<a href="#PowerBoard">Силовые щиты</a>', '<a href="#Engine">Двигатели</a>', ['<a href="#PlanetEngine">Планетарные</a>', '<a href="#HyperEngine">Межзвездные</a>'], '<a href="#Expand">Модули расширения</a>', '<a href="#Cargo">Грузовые отсеки</a>', [ '<a href="#Container">Контейнеры</a>', '<a href="#Hold">Трюмы</a>', '<a href="#FuelTank">Цистерны</a>', '<a href="#Hangar">Ангары</a>' ]], '<a href="#ShipCase">Корпуса</a>', '<a href="#Award">Медали</a>', '<a href="#BattleRank">Звания</a>' ]

        template_values = {
#            'url': url,
#            'url_linktext': url_linktext,
            'img_path': 'http://img.starquake.ru',
            'title': 'SQ Primerka',
            'keywords': 'SQ Primerka',
            'description': 'SQ Primerka',
            'url_img': 'http://img.starquake.ru',
            'url_css': 'http://img.starquake.ru/css',
            'moduleTypes': modlist,
            'moduleTypeList': menulist,
            'allowEdit': True,
            'allowBuy': True,
            }
     
        path = os.path.join(os.path.dirname(__file__), 'templates/list_own.html')
        data = template.render(path, template_values)
        return data

    def updateModule(self, module, name):
        text = self.request.get(name)
        if text is None:
            return False
        if len(text) <= 0:
            return False
        if not hasattr(module, name):
            return False
        value = int(text)
        if getattr(module, name) == value:
            return False
        setattr(module, name, value)
        return True

    def get(self):
        if not users.get_current_user():
            self.redirect('/')
            return

        self.response.out.write(self.get_page_data())

    def post(self):
        if not users.get_current_user():
            return

#        print "request = '%s'\n" % self.request

        mode = self.request.get('mode')
#        print "mode = '%s'\n" % mode
        key = self.request.get('key')
        action = self.request.get('action')
#        print "action = '%s'\n" % action
        if mode=='Edit':
            module = db.get(db.Key(key))
#            print module

            if action=='Save':
                items = ['status', 'deterioration', 'maxdeterioration', 'energy', 'speed', 'shield', 'protection', 'power', 'sensitivity', 'distance', 'rateoffire', 'od', 'accuracy', 'charge', 'maxcharge', 'timecount', 'radius', 'recharge', 'minshot', 'maxshot']
                updated = False
                for item in items:
                    updated |= self.updateModule(module, item)
                if updated:
                    module.put()
                self.redirect('/own')
            
            if isinstance(module, modules.Module):
                modulelist = [ module ]
            else:
                modulelist = []

            template_values = {
                'img_path': 'http://img.starquake.ru',
                'title': 'SQ Primerka',
                'keywords': 'SQ Primerka',
                'description': 'SQ Primerka',
                'url_img': 'http://img.starquake.ru',
                'url_css': 'http://img.starquake.ru/css',
                'moduleTypes': modulelist,
                'allowEdit': True,
                'allowBuy': True,
                'modeEdit': True,
                }
    
            path = os.path.join(os.path.dirname(__file__), 'templates/list_own.html')
            self.response.out.write(template.render(path, template_values))

        elif mode=='Delete':
            module = db.get(db.Key(key))
            if module is not None:
                module.status = 0
                module.put()
            self.get()


def main():
    application = webapp.WSGIApplication([('/own', MainHandler)], debug=True)
    wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
    main()
